package com.ajview.core.web.service;

import com.ajview.common.core.constant.Constants;
import com.ajview.common.core.domain.bo.LoginUser;
import com.ajview.common.core.domain.enums.ResultCodeEnum;
import com.ajview.common.core.exception.auth.AuthGlobalException;
import com.ajview.common.core.exception.auth.CaptchaException;
import com.ajview.common.utils.RedisUtils;
import com.ajview.common.utils.StringUtils;
import com.ajview.core.security.service.TokenService;
import com.ajview.system.service.SysConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author ZhangJunJie
 * @Date 2022-09-29
 * <p>
 * 概要：系统认证逻辑
 */
@Component
@Slf4j
public class SysLoginService {
    @Resource
    private AuthenticationManager authenticationManager;

    @Resource
    private TokenService tokenService;

    @Resource
    private SysConfigService sysConfigServiceImpl;

    @Resource
    private RedisUtils redisUtils;

    /**
     * 用户认证核心业务
     *
     * @param username 用户名
     * @param password 密码
     * @param code     验证码
     * @param uuid     验证码随机id
     * @return token
     */
    public String loginCore(String username, String password, String code, String uuid) {
        boolean captchaEnabled = sysConfigServiceImpl.selectCaptchaEnabled();
        // 验证码开关
        if (captchaEnabled) {
            validateCaptcha(username, code, uuid);
        }
        // 用户验证
        Authentication authentication;
        try {
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager
                    .authenticate(new UsernamePasswordAuthenticationToken(username, password));
        } catch (Exception e) {
            log.error("登录异常，" + e.getMessage());
            if (e instanceof BadCredentialsException) {
                throw new AuthGlobalException(ResultCodeEnum.LOGIN_AUTH_EXCEPTION.getMessage());
            } else {
                throw new AuthGlobalException(e.getMessage());
            }
        }
        // TODO:异步记录登录日志


        LoginUser loginUser = (LoginUser) authentication.getPrincipal();

        // TODO：同步修改用户信息到数据库


        return tokenService.createToken(loginUser);
    }

    /**
     * 校验验证码
     *
     * @param username 用户名
     * @param code     验证码
     * @param uuid     唯一标识
     * @return 结果
     */
    public void validateCaptcha(String username, String code, String uuid) {
        String verifyKey = Constants.CAPTCHA_CODE_KEY + StringUtils.nvl(uuid, "");
        String captcha = redisUtils.getCacheObject(verifyKey);
        redisUtils.del(verifyKey);
        if (StringUtils.isEmpty(captcha)) {
            throw new CaptchaException("user.verification-code.expire");
        }
        if (!code.equalsIgnoreCase(captcha)) {
            throw new CaptchaException("user.verification-code.error");
        }
    }

}
